package com.warmheart.base.interceptor;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.config.RedisService;
import com.warmheart.base.entity.Operator;
import com.warmheart.base.session.SessionLocalUtils;
import com.warmheart.core.constant.Globals;
import com.warmheart.core.enums.PlatEnum;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;
import com.warmheart.core.util.JsonResponseUtil;

/**
 * 
 * @ClassName: DuplicateSubmitInterceptor
 * @Description: 重复提交拦截器
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
public abstract class DuplicateSubmitInterceptor extends HandlerInterceptorAdapter {

    @Autowired(required = false)
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 仅拦截对方法的访问，对于其他静态资源不进行拦截
        if (handler instanceof HandlerMethod) {

            HandlerMethod method = (HandlerMethod) handler;
            Duplicate duplicate = method.getMethod().getAnnotation(Duplicate.class);

            // 如果防重复提交不为空
            if (duplicate != null && duplicate.validate()) {

                // 获取登录人
                Operator operator = SessionLocalUtils.getOperator();
                if (operator != null) {
                    String key = operator.getSessionId() + Globals.UNDER_LINE
                            + method.getBeanType().getName().toString() + Globals.UNDER_LINE
                            + method.getMethod().getName();
                    if (redisService.get(PlatEnum.RedisPrefix.PREFIX_WEB.getValue() + key) != null) {
                        JsonResponseUtil.writerJsonFromObj(response,
                                CommonResult.failed(ResultCode.DUPLICATE_SUBMIT, "操作过于频繁"));
                        return false;
                    }
                    // 不允许重复提交
                    if (duplicate.custom()) {
                        redisService.set(PlatEnum.RedisPrefix.PREFIX_WEB.getValue() + key, key, duplicate.clickTime(),
                                duplicate.timeUnit());
                    } else {
                        redisService.set(PlatEnum.RedisPrefix.PREFIX_WEB.getValue() + key, key, duplicateOnclickTime(),
                                TimeUnit.SECONDS);
                    }
                }

            }
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 
     * @Title: duplicateOnclickTime
     * @Description: 设置重复点击间隔
     * @author ZhangJianyang
     * @return
     */
    public abstract Integer duplicateOnclickTime();
}
